<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models;
use App\Modeldetail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\QueryException;

class ModelsController
{
	function add()
	{
		return view('admin.models.add');
	}
	function doadd(Request $request)
	{
		$arr = $request->all();
		//写表models数据
		DB::beginTransaction();
		$ob = Models::create($arr);
		$createTableSql = "create table cms_{$arr['tablename']}(id int key auto_increment,";
		if (is_object($ob)) {
			//写modeldetail
			$result = true;
			$fieldList = "";
			foreach ($arr['fieldname'] as $k => $v) {
				$fieldList .= ",'" . $v . "'";
				$detailArr['fieldname'] = $v;
				if (strlen($v) == 0) {
					continue;
				}
				$detailArr['cname'] = isset($arr['cname'][$k]) ? $arr['cname'][$k] : '';
				$detailArr['type'] = isset($arr['type'][$k]) ? $arr['type'][$k] : '';
				$detailArr['length'] = isset($arr['length'][$k]) ? $arr['length'][$k] : 0;
				$detailArr['defaultvalue'] = isset($arr['defaultvalue'][$k]) ? $arr['defaultvalue'][$k] : '';
				$detailArr['kvalue'] = isset($arr['kvalue'][$k]) ? $arr['kvalue'][$k] : '';
				$detailArr['constraints'] = isset($arr['constraint'][$k]) ? implode(',', $arr['constraint'][$k]) : '';
				$detailArr['modelsid'] = $ob->id;
				$re = Modeldetail::create($detailArr);
				$createTableSql .= $detailArr['fieldname'] . " " . $detailArr['type'];
				if ($detailArr['length']) {
					$createTableSql .= "({$detailArr['length']})";
				}
				if (isset($arr['constraint'][$k])) {
					foreach ($arr['constraint'][$k] as $conValue) {
						if ($conValue == 'unique' || $conValue == 'unsigned') {
							$createTableSql .= ' ' . $conValue . " ";
						}
					}
				}
				$createTableSql .= ",";
				if (!$re) {
					$result = false;
					break;
				}
			}
			if ($result) { //modeldetail表操作成功
				DB::commit();
				//生成模型表
				$createTableSql = substr($createTableSql, 0, -1);
				$createTableSql .= ")";
				try {
					$createResult = DB::statement($createTableSql);
					$message = $createResult ? "模型表创建成功" : "模型表创建失败";
				} catch (QueryException $e) {
					DB::rollback();
					Models::where('id', $ob->id)->first()->delete();
					return response()->json(['result' => 'error', 'message' => $e]);
				}
				//生成数据模型类
				//确定类文件名称
				$fileName = ucfirst($arr['tablename']) . ".php";
				//类名
				$className = ucfirst($arr['tablename']);
				//类代码
				$fieldList = substr($fieldList, 1);
				$classContent = <<<EOF
<?php 
namespace App;
use Illuminate\Database\Eloquent\Model;
class {$className} extends Model{
	protected \$table = "{$arr['tablename']}";
	public \$timestamps = false;
	public \$fillable = [{$fieldList}];
}
EOF;
				Storage::disk('app')->put($fileName, $classContent);
				return response()->json(['result' => 'success', 'message' => $message . ",保存成功"]);
			} else {
				DB::rollback();
				return response()->json(['result' => 'error', 'message' => "写模型详情失败"]);
			}
		} else {
			DB::rollback();
			return response()->json(['result' => 'error', 'message' => "写模型失败"]);
		}
	}
	function index()
	{
		//获取模型列表数据
		$cols = Models::orderBy('id', 'desc')->paginate(3);
		//呈现管理列表模板
		return view('admin.models.index', ['cols' => $cols]);
	}
	function edit($id)
	{
		//根据id，获取模型记录
		$models = Models::find($id);
		//根据id，获取模型详细记录
		$modelDetailCols = Modeldetail::where("modelsid", $id)->get();
		//呈现模板
		return view('admin/models/edit', ['models' => $models, 'modelDetailCols' => $modelDetailCols]);
	}
	function doedit(Request $request)
	{
		$arr = $request->all();

		//保存models
		$modelsid = $arr['modelsid'];
		$modelsArr = [
			'namer' => $arr['namer'],
			//'tablename'=>$arr['tablename'],//表单中不允许修改
			'isimages' => $arr['isimages']
		];
		DB::beginTransaction();
		$re = Models::where("id", $modelsid)->update($modelsArr);
		//保存modeldetail
		if ($re !== false) {
			$result = true;
			$fieldList = "";
			foreach ($arr['fieldname'] as $k => $v) {
				$detailArr['fieldname'] = $v;
				if (strlen($v) == 0) {
					continue;
				}
				$fieldList .= ",'" . $v . "'";
				$detailArr['cname'] = isset($arr['cname'][$k]) ? $arr['cname'][$k] : '';
				$detailArr['type'] = isset($arr['type'][$k]) ? $arr['type'][$k] : '';
				$detailArr['length'] = isset($arr['length'][$k]) ? $arr['length'][$k] : 0;
				$detailArr['defaultvalue'] = isset($arr['defaultvalue'][$k]) ? $arr['defaultvalue'][$k] : '';
				$detailArr['kvalue'] = isset($arr['kvalue'][$k]) ? $arr['kvalue'][$k] : '';
				$detailArr['constraints'] = isset($arr['constraint'][$k]) ? implode(',', $arr['constraint'][$k]) : '';
				$detailArr['modelsid'] = $modelsid;
				if (isset($arr['modeldetailid'][$k])) { //修改
					$ren = Modeldetail::where("id", $arr['modeldetailid'][$k])->update($detailArr);
					//如果修改成功，同步到对应的模型表中
					//alter table 表名 change old字段 新名称 类型(长度) unique unsigned
					if ($ren > 0) {
						$sql = "alter table cms_{$arr['tablename']} change {$arr['oldfieldname'][$k]} {$detailArr['fieldname']} {$detailArr['type']}";
						if ($detailArr['length']) {
							$sql .= "({$detailArr['length']}) ";
						}
						if (isset($arr['constraint'][$k])) {
							foreach ($arr['constraint'][$k] as $conValue) {
								if ($conValue == 'unique' || $conValue == 'unsigned') {
									$sql .= " " . $conValue . " ";
								}
							}
						}
						DB::statement($sql);
					}
				} else {
					$ren = Modeldetail::create($detailArr);
					//如果修改成功，同步到对应的模型表中
					//alert table 表名 add 字段名 类型(长度) unique unsigned
					if ($ren) {
						$sql = "alter table cms_{$arr['tablename']} add {$detailArr['fieldname']} {$detailArr['type']}";
						if ($detailArr['length']) {
							$sql .= "({$detailArr['length']}) ";
						}
						if (isset($arr['constraint'][$k])) {
							foreach ($arr['constraint'][$k] as $conValue) {
								if ($conValue == 'unique' || $conValue == 'unsigned') {
									$sql .= " " . $conValue . " ";
								}
							}
						}
						DB::statement($sql);
					}
				}
				$message = $ren === false ? "修改失败" : "修改成功";
				if ($ren === false) {
					$result = false;
					break;
				}
			}
			if ($result === false) {
				DB::rollback();
				return response()->json(['result' => 'error', 'message' => $message]);
			} else {
				//同步此数据模型对应的类
				$className = ucfirst($arr['tablename']);
				$fileName = $className . ".php";
				$fieldList = substr($fieldList, 1);
				$classContent = <<<EOF
<?php 
namespace App;
use Illuminate\Database\Eloquent\Model;
class {$className} extends Model{
	protected \$table = "{$arr['tablename']}";
	public \$timestamps = false;
	public \$fillable = [{$fieldList}];
}
EOF;
				Storage::disk('app')->put($fileName, $classContent);
				DB::commit();
				return response()->json(['result' => 'success', 'message' => $message]);
			}
		} else {
			DB::rollback();
			return response()->json(['result' => 'error', 'message' => "模型修改失败"]);
		}
	}
	function dodel($id)
	{

		$ob = Modeldetail::where('id', $id)->first();

		$fieldname = $ob->fieldname;
		$modelsid = $ob->modelsid;
		//根据值，去删除表中记录
		$re = $ob->delete();


		if ($re) {
			//修改内容表结构，删除内容表响应的字段
			//alter table 表名 drop 字段名;
			//找表名
			$modelsOb = Models::where('id', $modelsid)->first();
			$tablename = $modelsOb->tablename;
			$sql = "alter table cms_{$tablename} drop $fieldname";
			$ren = DB::statement($sql);
			if ($ren) {
				//处理对应的类
				$classContent = Storage::disk('app')->get(ucfirst($tablename) . '.php');
				//处理fillable对应的内容
				$classContent = preg_replace("/(\\\$fillable = \[[\w,]*)'{$fieldname}'/", '$1', $classContent);
				$classContent = preg_replace("/,,/", ',', $classContent);
				$classContent = preg_replace("/\[,/", '[', $classContent);
				$classContent = preg_replace("/,\]/", ']', $classContent);
				Storage::disk('app')->put(ucfirst($tablename) . '.php', $classContent);
			}
			return response()->json(['result' => 'success', 'message' => '删除成功']);
		} else {
			return response()->json(['result' => 'error', 'message' => '删除失败']);
		}
	}
	// 模型记录的删除  删除models表中记录 modeldetail中记录 删除数据模型类文件
	function del($id)
	{
		//模型记录的删除
		DB::beginTransaction();
		$ob = Models::where('id', $id)->first();
		$tablename = $ob->tablename;
		$re = $ob->delete();
		if ($re) {
			//删除模型内容表
			try {
				DB::statement("drop table cms_" . $tablename);
			} catch (QueryException $e) {
				$message = "删除失败";
			}
			$re1 = Modeldetail::where('modelsid', $id)->delete();
			if ($re1) {
				DB::commit();
				//删除数据模型类文件
				//获取文件的名称
				@unlink(base_path('app') . "/" . ucfirst($tablename) . ".php");
				$message = "删除成功";
			} else {
				DB::rollback();
				$message = "删除失败";
			}
		} else {
			DB::rollback();
			$message = "删除失败";
		}

		return redirect()->back()->with('message', $message);
	}
}
